<?php

class Portfolio_model extends CI_Model {

    public function __construct() {
        parent::__construct();
    }

    public function get_portfolio($slug = FALSE) {
        if ($slug === FALSE) {
            $query = $this->db->get('portfolio');
        } else {
            $query = $this->db->get_where('portfolio', array('slug' => $slug));
        }
        $por_array = $query->result_array();
        $result = array();
        foreach ($por_array as $por_item) {
            $por_cat = $this->get_por_cat($por_item['id']);
            $por_item['category'] = $por_cat;

            $por_img = $this->get_por_img($por_item['id']);
            $por_item['img'] = $por_img;

            array_push($result, $por_item);
        }
//        return $por_array;
        return $result;
    }

    public function get_latest_portfolio($quantity = FALSE) {
        if ($quantity === FALSE) {
            $quantity = 4;
        }
        $this->db->order_by('created_date', 'desc');
        $this->db->limit($quantity);
        $query = $this->db->get('portfolio');
        $pors = $query->result_array();

        $result = array();
        foreach ($pors as $por) {
            $por_cat = $this->get_por_cat($por['id']);
            $por['category'] = $por_cat;

            $por_img = $this->get_por_img($por['id']);
            $por['img'] = $por_img;

            array_push($result, $por);
        }

        return $result;
    }

    public function set_portfolio($data) {
        return $this->db->insert('message', $data);
    }

    /**
     *
     * @param object data = array('portfolio_id', 'img_url')
     * @return type
     */
    public function set_por_img($data) {
        return $this->db->insert('por_img_relation', $data);
    }

    /**
     *
     * @param int $id
     * @return all img of that portfolio
     */
    public function get_por_img($id) {
        $query = $this->db->get_where('por_img_relation', array('portfolio_id' => $id));
        return $query->result_array();
    }

    public function get_category() {
        $query = $this->db->get('portfolio_category');
        return $query->result_array();
    }

    public function get_por_cat($id) {
        $query = $this->db->get_where('por_cat_relation', array('portfolio_id' => $id));
        return $query->result_array();
    }

    public function set_por_cat($data) {
        return $this->db->insert('por_cat_relation', $data);
    }

}
